package com.zl.tby.core.context.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zl.tby.core.context.bean.DictBean;
import com.zl.tby.core.context.bean.DictResult;
import com.zl.tby.core.context.tools.HttpURLConnectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.wood.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UC不需要登录的接口
 * @author changpeng
 * @since 2025/11/5 9:22
 */
@Slf4j
@Component
public class UcService {
    @Inject("${server.uc-url}")
    private String ucUrl;

    /**
     * 根据编码获取字典
     * @param dictType
     * @return
     */
    public List<DictBean> getDict(String dictType) {
        if (StringUtils.isEmpty(dictType)) {
            return new ArrayList<>();
        }
        try {
            Map<String, String> param = new HashMap<>();
            param.put("type", dictType);
            String response = HttpURLConnectionUtil.sendGet(ucUrl + "/dict/type", param);
            Gson gson = new Gson();
            DictResult<DictBean> result = gson.fromJson(response, new TypeToken<DictResult<DictBean>>() {}.getType());
            return result.getData();
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("后台请求后台字典接口异常, dictType: " + dictType, ex);
            return new ArrayList<>();
        }
    }

    public Map<String, String> getDictMap(String dictType) {
        Map<String, String> map = new HashMap<>(0);
        List<DictBean> dictList = getDict(dictType);
        if (dictList != null) {
            dictList.forEach(item -> {
                map.put(item.getValue(), item.getLabel());
            });
        }
        return map;
    }
}
